<?php

namespace app\api\controller;

use app\api\service\Activity\AssociationJobsDetectionService;
use app\api\service\Activity\AssociationJobsService;
use app\common\controller\Api;
use app\common\model\Circle;
use app\common\model\circle\Answer;
use app\common\model\circle\Cate;
use app\common\model\circle\Notice;
use app\common\model\circle\Noticelog;
use app\common\model\circle\Position;
use app\common\model\circle\Topic;
use app\common\model\circle\Liyou;
use app\common\model\circle\User as CircleUser;
use app\common\model\publics\Banner;
use app\common\model\publics\Follow;
use app\common\model\publics\Huati;
use app\common\model\publics\Likecoll;
use app\common\model\trends\Comment;
use app\common\model\trends\Cate2;
use app\common\model\Scenic;
use app\common\model\trends\Friends;
use app\common\model\trends\Huati as TrendsHuati;
use app\common\model\trends\Cate as TrendsCate;
use app\common\model\trends\Banner as Banner2;
use app\common\model\User;
use app\common\model\Scenic2;
use think\Config;
use think\Db;
use think\Log;

/**
 * 动态信息接口
 */
class Trends extends Api
{
	protected $noNeedLogin = ['trends_detail','comment_list','get_anony','get_scenic_list','video_comment_list'];
	protected $noNeedRight = ['*'];

	/**
     * 获取加入圈子的方式
     * 
	 * @ApiMethod (POST)
	 * @param int $type  类型，必填 （1 理由，2 题库）
	 * @param int $circle_id 圈子id，必填
     */
	public function get_topic() {
		$user_id = $this->auth->id;
		$type = $this->request->post('type');
		$circle_id = $this->request->post('circle_id', 0);
		if($type == 1){
			$list = Liyou::where(['circle_id'=>$circle_id])->select();
		}elseif ($type == 2){
			$list = Topic::where(['circle_id'=>$circle_id])->select();
		}else{
			$this->success("参数错误",[],2);
		}
		$this->success("获取成功",$list);
	}

	/**
	 * 选择匿名
	 */
	public function get_anony()
	{
		$site = Config::get("site2");
		$key = rand(1, count($site['anony']));
		$day = date("Y-m-d");
		if ($day == $this->auth->anony_day) {
			$this->success('一天只能换一次', $this->auth->anony, 2);
		}
		$this->success('请求成功', $site['anony'][$key]);
	}

	/**
	 * 保存匿名
     * 
	 * @ApiMethod (POST)
	 * @param string $anony  匿名名称，必填
	 */
	public function save_anony()
	{
		$anony = $this->request->post('anony');
		if (!$anony) {
			$this->success('匿名不能为空', [], 2);
		}
		$day = date("Y-m-d");
//	    if($day == $this->auth->anony_day){
//		    $this->success('一天只能换一次',$this->auth->anony,2);
//	    }
		$user = \app\common\model\User::get($this->auth->id);
		$user->save(['anony_day' => $day, 'anony' => $anony, 'update_time' => time()]);
		$this->success('保存成功', $user);
	}

	/**
	 * 获取位置
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id，必填
	 */
	public function get_position()
	{
		$circle_id = $this->request->post('circle_id');
		$list = Position::where(['circle_id' => $circle_id])->order('weigh desc')->select();
		$this->success('请求成功', $list);
	}

	/**
	 * 获取分类
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id 圈子id，必填
	 */
	public function trends_cate()
	{
		$circle_id = $this->request->post('circle_id', 1);
		$list = Cate2::where(['circle_id' => $circle_id, 'is_show' => 1])
		             ->order('is_sort asc,weigh asc')
		             ->select();
		foreach ($list as $k => $v) {
			$v->append(['is_name']);
			if ($v->is_sort == 1) {
				$v->is_name = TrendsCate::where(['id' => $v->cate_id])->value('is_name');
			} else {
				$v->is_name = 2;
			}
		}
		$this->success('请求成功', $list);
	}

	/**
	 * 话题列表
     * 
	 * @ApiMethod (POST)
	 * @param string $title  名称
	 * @param int $page 当前页码
	 * @param int $count 每页数量
	 */
	public function huati_list()
	{
		$title = $this->request->post('title');
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);

		$where = [];
		if ($title) {
			$where['title'] = array('like', "%$title%");
		}

		$list = Huati::where($where)
		             ->order("id desc")
		             ->paginate($count, false, ["page" => $page]);

		$this->success("", $list);
	}

	/**
	 * 添加话题
     * 
	 * @ApiMethod (POST)
	 * @param string $title  话题名称
	 */
	public function add_huati()
	{
		$user_id = $this->auth->id;
		$title = $this->request->post('title');

		if (empty($title)) {
			$this->success("请输入话题", [], 2);
		}

		$huati = Huati::where(['title' => $title])->find();
		if ($huati) {
			$this->success("话题已存在", [], 2);
		}
		$res = Huati::create(['user_id' => $user_id, 'title' => $title, 'createtime' => time()]);
		if ($res) {
			$this->success("成功");
		} else {
			$this->error("添加失败");
		}
	}

	/**
	 * 好友列表、我关注的人
     * 
	 * @ApiMethod (POST)
	 * @param string $title  好友名称
	 * @param int $page 当前页码
	 * @param int $count 每页数量
	 */
	public function haoyou_list()
	{
		$user_id = $this->auth->id;
		$nickname = $this->request->post('title', "");
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);

		$where = [];
		$where['follow.user_id'] = $user_id;
		if ($nickname) {
			$where['user.nickname'] = array('like', "%$nickname%");
		}

		$list = Follow::with(['user'])
		              ->where($where)
		              ->order("createtime desc")
		              ->paginate($count, false, ["page" => $page]);

		foreach ($list as $row) {
			$row->visible(['id', 'user2_id', 'createtime']);
			$row->visible(['user']);
			$row->getRelation('user')
			    ->visible(['nickname', 'avatar']);
		}
		$this->success("成功", $list);
	}

	/**
	 * 发布动态
     * 
	 * @ApiMethod (POST)
	 * @param 动态对象数组
	 */
	public function fabu_trends()
	{
		$param = $this->request->param();
		$id = $this->request->post('id', 0);
		$unique_id = $this->request->post('unique_id', 0);
		$this->rule = [
			"circle_id|圈子ID"   => ["require"],
			"title|标题"         => ["require"],
			//"position_id|位置ID" => ["require"],
			//"cate_id|分类ID"     => ["require"],
			//"detail|内容"        => ["require"],
			"is_draft|是否草稿"  => ["require"]
		];

		/*if(!empty($param['title']) || !empty($param['detail'])){
			$msg = keyword($param['title'].$param['detail']);
			if($msg){
				$this->success('很抱歉，标题或正文中不能包含敏感词汇:'.$msg, [], 2);
			}
		}*/
		//if(!empty($param['title']) || !empty($param['detail'])){
		//$this->error("测试", $param);
		if(!empty($param['title'])){
			$msg = keyword($param['title']);
			if(!empty($param['detail'])) {
				$msg = keyword($param['title'].$param['detail']);
			}
			if($msg){
				$this->success('很抱歉，标题或正文中不能包含敏感词汇:'.$msg, [], 2);
			}
		}

		if ($param['is_draft'] == 2) {
			$this->checks($param);
			$circle = Circle::get($param['circle_id']);
		
			if(!$circle){
				$this->success('圈子不存在',[],2);
			}
			$param["state"] = 1;
			//圈子审核开关
			if($circle->is_open == 1){
				$param["state"] = 4;
			}
			//平台审核开关
			$site_dt_open = Config::get("site2.dt_open");
			if($site_dt_open == 1){
				$param["state"] = 4;
			}
			//个人审核开关
			if($this->auth->dt_open == 1){
				$param["state"] = 4;
			}
			if($unique_id){
                $param["state"] = 4;
            }

		}
		$param["position_name"] = Position::where(['id' => $param["position_id"]])->value('name');
		$param["cate_name"] = Cate2::where(['id' => $param["cate_id"]])->value('name');
		$param["user_id"] = $this->auth->id;
		unset($param["id"]);
		if ($id > 0) {
			$trends = \app\common\model\Trends::get($id);
			if (!$trends) {
				$this->success('信息不存在', [], 2);
			}
			$res = $trends->save($param);
    		if($trends['state'] == 1){
    		  	$this->success('提交成功');  
    		}
		} else {
            $param["create_time"] = time();
			$res = \app\common\model\Trends::create($param, true);
		}
		
		if ($res) {
			$list = json_decode(html_entity_decode($param['huati_text']), true);
			if (count($list) > 0 && $param['is_draft'] == 2) {
				foreach ($list as $k => $v) {
					\app\common\model\trends\Huati::insert(['huati_id' => $v['id'], 'title' => $v['name'], 'trends_id' => $res->id, 'createtime' => time()]);
				}
			}

			$list2 = json_decode(html_entity_decode($param['hy_text']), true);
			if (count($list2) > 0 && $param['is_draft'] == 2) {
				foreach ($list2 as $k2 => $v2) {
					Friends::insert(['senduser_id' => $this->auth->id, 'user_id' => $v2['id'], 'nickname' => $v2['name'], 'trends_id' => $res->id, 'createtime' => time()]);
				}
			}

			if ($param['is_draft'] == 2) {
				//经验奖励
				exps($param['circle_id'], $this->auth->id, 3);
			}
			/*关联了活动任务*/
//			if($unique_id){
//                /*状态：正常；谁可见：公开；不是草稿*/
//                if($param["state"] == 1 && $param["is_see"] == 1 && $param['is_draft'] == 2){
//                    /*执行任务匹配*/
//                    $res = AssociationJobsDetectionService::index($unique_id, $res->id);
//                }
//            }

			$this->success('提交成功');
		} else {
			$this->error("出差了");
		}
	}

	/**
	 * 点赞收藏
     * 
	 * @ApiMethod (POST)
	 * @param int $type     类型 （ 1=like，2=coll）
	 * @param int $trends_id 动态id
	 */
	public function like()
	{
		$user_id = $this->auth->id;
		$type = $this->request->post('type');
		$trends_id = $this->request->post('trends_id');
		if (empty($type) || empty($trends_id)) {
			$this->success('参数错误', [], 2);
		}

		$join = $type == 1 ? "like" : "coll";
		$trends = \app\common\model\Trends::get($trends_id);
		if (!$trends) {
			$this->success('动态不存在', [], 2);
		}
//		if ($user_id == $trends->user_id) {
//			$this->success('不可点赞或收藏自己的文章', [], 2);
//		}
		$colllike = Likecoll::where(['type' => $type, 'user_id' => $user_id, 'trends_id' => $trends_id])->find();
		Db::startTrans();
		$arr = [];
		if ($colllike) {
			$arr[] = $colllike->delete();
			$arr[] = $trends->setDec($join, 1);
			$arr[] = \app\common\model\User::where(['id' => $trends->user_id])->setDec($join."_num", 1);
		} else {
			$arr[] = Likecoll::create(["user_id" => $user_id, "user2_id" => $trends->user_id, "trends_id" => $trends_id, "circle_id" => $trends->circle_id, "type" => $type, "createtime" => time()]);
			$arr[] = $trends->setInc($join, 1);
			$arr[] = \app\common\model\User::where(['id' => $trends->user_id])->setInc($join."_num", 1);
			//点赞发送系统消息
			send($user_id,$trends->user_id,1,0);
			//动态点赞经验奖励
			exps($trends->circle_id, $user_id, 10, 2);
			//动态被点赞经验奖励
			exps($trends->circle_id, $trends->user_id, 6, 2);
		}

		if (in_array(false, $arr)) {
			Db::startTrans();
			$this->error("出差了");
		} else {
			Db::commit();
			$this->success('成功', $arr);
		}
	}

	/**
	 * 动态热榜
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id  圈子id
	 * @param int $page       当前页码
	 * @param int $count      每页数量
	 */
	public function hot_trends()
	{
		$user_id = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 1);
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);
		$circles_id = Config::get("site2.ggqz");//公共圈子

		$where = [];
		$where['is_draft'] = 2;
		$where['state'] = 1;
		if ($circle_id > 1) {
			$where['circle_id'] = $circle_id;
		}

		$list = \app\common\model\Trends::where($where)
			//->whereTime("create_time",$wheretime)
			                            ->order('vc_sum desc')
		                                ->limit(20)
		                                ->select();
		foreach ($list as $v) {
			$v->append(['userinfo']);
			$v->userinfo = getuser($v,$user_id,$circles_id);
		}
		$this->success("", $list);
	}

	/**
	 * 热门话题
	 */
	public function hot_huati()
	{
		$list = \app\common\model\publics\Huati::order('vc_sum desc')
		             ->limit(20)
		             ->select();
		$this->success('成功', $list);
	}

	/**
	 * 关注
     * 
	 * @ApiMethod (POST)
	 * @param int $user_id    被关注用户id
	 */
	public function follow()
	{
		$user_id = $this->auth->id;
		$user2_id = $this->request->post('user_id');
		if (empty($user2_id)) {
			$this->success('参数错误', [], 2);
		}
		//自己
		$user = user::get($user_id);
		//被关注用户
		$user2 = user::get($user2_id);
		if (!$user2) {
			$this->success('用户不存在', [], 2);
		}
		if ($user_id == $user2_id) {
			$this->success('自己不能关注自己', [], 2);
		}

		$follow = Follow::where(['user_id' => $user_id, 'user2_id' => $user2_id])->find();

		Db::startTrans();
		$arr = [];
		if ($follow) {
			$arr[] = $follow->delete();
			$arr[] = $user2->setDec('fans', 1);//减少粉丝
			$arr[] = $user->setDec('follow', 1);//减少关注
		} else {
			$arr[] = Follow::create(['user_id' => $user_id, 'user2_id' => $user2_id, "createtime" => time()]);
			$arr[] = $user2->setInc('fans', 1);//增加粉丝
			$arr[] = $user->setInc('follow', 1);//自己
		}

		if (in_array(false, $arr)) {
			Db::startTrans();
			$this->error("出差了");
		} else {
			Db::commit();
			$this->success('成功');
		}
	}

	/**
	 * 话题列表
     * 
	 * @ApiMethod (POST)
	 * @param int $huati_id   话题id
	 * @param int $type       排序类型 （1=huati.createtime desc）
	 * @param int $page       当前页码
	 * @param int $count      每页数量
	 */
	public function huati_home()
	{
		$user_id = $this->auth->id;
		//$user_id = 76;
		$huati_id = $this->request->post('huati_id', 0);
		$type = $this->request->post('type', 1);
		$page = $this->request->post('page', 1);
		$count = $this->request->post('count', 10);

		$where = [];
		$where['huati.huati_id'] = $huati_id;
		$where['trends.state'] = 1;
		$circles_id = Config::get("site2.ggqz");//公共圈子

		if ($type == 1) {
			$order = "huati.createtime desc";
		} else {
			$order = "";
		}

		$list = \app\common\model\trends\Huati::with(['trends'])->where($where)->order($order)->paginate($count, false, ["page" => $page]);
		foreach ($list as $v) {
			$v->visible(['id', 'huati_id', 'title', 'trends_id', 'view', 'comment', 'createtime']);
			$v->visible(['trends']);
			$v->trends->append(['userinfo']);
			$v->trends->userinfo = getuser($v->trends,$user_id,$circles_id);
		}
		$this->success("", $list);
	}

	/**
	 * 话题列表详情
     * 
	 * @ApiMethod (POST)
	 * @param int $huati_id   话题id，必填
	 */
	public function huati_detail()
	{
		$user_id = $this->auth->id;
		$huati_id = $this->request->post('huati_id');
		if (!$huati_id) {
			$this->error('参数错误');
		}
		$huati = \app\common\model\publics\Huati::where(['id' => $huati_id])->find();
		if (empty($huati)) {
			$this->success('无数据', [], 2);
		}
		$huati->setInc('view', 1);
//		$huati->append(['view','comment']);
//		$huati->view = Db::name('trends_huati')->where(['huati_id'=>$huati->id])->sum('view');
//		$huati->comment = Db::name('trends_huati')->where(['huati_id'=>$huati->id])->sum('comment');
		$this->success('成功', $huati);
	}

	/**
	 * 置顶或调整分区
     * 
	 * @ApiMethod (POST)
	 * @param int $type      类型 （1 置顶，2 调整分区）
	 * @param int $is_top    是否置顶: 1=是,2=否
	 * @param int $trends_id 动态id，必填
	 * @param int $cate_id   分类id
	 */
	public function Topping()
	{
		$user_id = $this->auth->id;
		$type = $this->request->post('type');
		$is_top = $this->request->post('is_top');
		$trends_id = $this->request->post('trends_id', 0);
		$cate_id = $this->request->post('cate_id');

		$trends = \app\common\model\Trends::get($trends_id);
		if (!$trends) {
			$this->success("动态不存在", [], 2);
		}
	
		$userinfo = getuser($trends, $user_id, $trends->circle_id);

		$circle = CircleUser::where(['user_id' => $user_id, 'circle_id' => $trends->circle_id])->find();
		if (!$circle) {
			$this->success('无权限', [], 2);
		}
		if ($circle->identity > 2) {
			$this->success('无权限', [], 2);
		}

		if ($type == 1) {
			$res = $trends->save(['is_top' => $is_top, 'updatetime' => time()]);
			//动态置顶经验奖励
			exps($trends->circle_id, $trends->user_id, 7, 2);
		} else {
			$cate_name = Cate2::where(['id' => $cate_id])->value('name');
			$res = $trends->save(['cate_id' => $cate_id, 'cate_name' => $cate_name, 'updatetime' => time()]);
		}

		if ($res) {
			$this->success("成功");
		} else {
			$this->error('出差了');
		}
	}

	/**
	 * 圈子申请
     * 
	 * @ApiMethod (POST)
	 * @param 圈子对象数组
	 */
	public function apply_circle()
	{
		$param = $this->request->param();
		$id = $this->request->post('id', 0);
		$this->rule = [
			"logo_image|Logo"    => ["require"],
			"name|圈子名称"          => ["require"],
			"lx_name|姓名"         => ["require"],
			"lx_mobile|联系电话"         => ["require"],
			"area|省市区"         => ["require"],
			"address|详细地址"         => ["require"],
			"circlecate_id|分类ID" => ["require"],
			"yuanyin|申请原因"       => ["require"]

		];

		$this->checks($param);

		$param["user_id"] = $this->auth->id;
		$param["create_time"] = time();

		$name = Circle::where(['name'=>$param["name"],'status'=>array('in','1,2')])->find();
		if($name){
			$this->success('该圈子名称已存在，请更改后重新申请~', [], 2);
		}

		if ($id > 0) {
			$trends = Circle::get($param['id']);
			if (!$trends) {
				$this->success('信息不存在', [], 2);
			}
			$param["state"] = 1;
			$res = $trends->save($param);
		} else {
			$param["logo_time"] = time();
			$res = Circle::create($param, true);
		}

		if ($res) {
			$this->success('圈子申请提交成功，请等待平台审核');
		} else {
			$this->error("出差了");
		}
	}

	/**
	 * 举报动态和圈友
     * 
	 * @ApiMethod (POST)
	 * @param 举报信息对象数组
	 */
	public function report()
	{
		$user_id = $this->auth->id;
		$param = $this->request->param();

		$this->rule = [
			//"circle_id|圈子id"         => ["require"],
			"jb_user_id|被举报用户id" => ["require"],
			"type|举报类型"          => ["require"],
			"yuanyin|举报原因"       => ["require"],
			"describe|举报描述"      => ["require"],
			//"images|举报材料"        => ["require"]

		];

		if ($param['type'] == 1) {
			$this->rule = [
				"trends_id|动态ID" => ["require"]
			];
		}

		$this->checks($param);

		$param["user_id"] = $user_id;
		$param["create_time"] = time();

		$res = \app\common\model\publics\Report::create($param, true);

		if ($res) {
			$this->success('举报成功');
		} else {
			$this->error("出差了");
		}
	}

	/**
	 * 动态详情
     * 
	 * @ApiMethod (POST)
	 * @param int $trends_id 动态id，必填
	 */
	public function trends_detail()
	{
		$user_id = $this->auth->id;
		$trends_id = $this->request->post('trends_id');

		$detail = \app\common\model\Trends::where(['id' => $trends_id])->find();

		if (!$detail) {
			$this->success("动态不存在或已删除...", [], 2);
		}

		$detail->append(['userinfo', 'banner']);
		$detail->userinfo = getuser($detail,$user_id,Config::get("site2.ggqz"));
		$detail->banner = Banner2::where(['circle_id' => $detail->circle_id,'status'=>2])
		                        ->order("is_platform asc,weigh asc")
		                        ->select();
		$detail->setInc('view', 1);
		$detail->setInc('vc_sum', 1);
		$detail->position_name = $detail->position_id>0?$detail->position_name:'全部校区';
		$detail->cate_name = $detail->cate_id>0?$detail->cate_name:'全部分类';
		//增加话题浏览量
		$list = \app\common\model\trends\Huati::where(['trends_id' => $trends_id])
		                                      ->select();
		foreach ($list as $k => $v) {
			$huati = Huati::get($v->huati_id);
			if ($huati) {
				$huati->setInc('view', 1);
				$huati->setInc('vc_sum', 1);
			}
		}
		  
		if(!strpos($detail->goods_id, ',')) {
		    $scenicModel = new Scenic();
			$scenics = $scenicModel->where(['id'=>$detail->goods_id])->find();
			//print_r($scenics);
			$detail->scenic_imags = $scenics['scenic_images'];
			$detail->scenic_address = $scenics['address'];
		}
		$this->success("", $detail);
	}

	//上级评论循环增加点赞数量
	private function circulate($parent_id)
	{
		$comment = Comment::get($parent_id);
		if ($comment) {
			$comment->setInc('num', 1);
			if ($comment->parent_id) {
				$this->circulate($comment->parent_id);
			}

		}
		return true;
	}

	/**
	 * 评论点赞
     * 
	 * @ApiMethod (POST)
	 * @param int $type       类型，必填 （3=点赞动态评论,4=点赞商品评论）
	 * @param int $comment_id 评论id，必填
	 */
	public function comment_like()
	{
		$user_id = $this->auth->id;
		$type = $this->request->post('type');//3=点赞动态评论,4=点赞商品评论
		$comment_id = $this->request->post('comment_id');

		if (empty($comment_id) || empty($type)) {
			$this->success('参数错误', [], 2);
		}
		$comment = Comment::get($comment_id);
		if (!$comment) {
			$this->success('评论不存在', [], 2);
		}
		if($type == 3 && $comment->type != 1){
			$this->success('点赞动态评论参数错误', [], 2);
		}
		if($type == 4 && $comment->type != 2){
			$this->success('点赞商品评论参数错误', [], 2);
		}
		$colllike = Likecoll::where(['type' => $type, 'user_id' => $user_id, 'comment_id' => $comment_id])->find();
		Db::startTrans();
		$arr = [];

		if ($colllike) {
			$arr[] = $colllike->delete();
			$arr[] = $comment->setDec('like', 1);
			$arr[] = User::where(['id' => $comment->user_id])->setDec('like', 1);
		} else {
			$arr[] = Likecoll::create(["user_id" => $user_id,
			                           "user2_id" => $comment->user_id,
			                           "comment_id" => $comment_id,
			                           'trends_id'=>$type==3?$comment->trends_id:0,
			                           'goods_id'=>$type==4?$comment->trends_id:0,
			                           'circle_id' => $comment->circle_id,
			                           "type" => $type,
			                           "createtime" => time()]);
			$arr[] = $comment->setInc('like', 1);
			$arr[] = User::where(['id' => $comment->user_id])->setInc('like_num', 1);
			//点赞发送系统消息
			send($user_id,$comment->user_id,1,0);
		}

		if (in_array(false, $arr)) {
			Db::startTrans();
			$this->error("出差了");
		} else {
			Db::commit();
			$this->success('成功');
		}
	}

	/**
     * 发布评论
     * 
	 * @ApiMethod (POST)
	 * @param int $parent_id  上级id
	 * @param int $trends_id  动态id，必填
	 * @param int $content    评论内容，必填
	 * 
	 * TODO 限制评论次数
     */
	public function add_comment()
	{
		$user_id = $this->auth->id;
		$parent_id = $this->request->post('parent_id', 0);
		$trends_id = $this->request->post('trends_id');
		$content = $this->request->post('content',"");

		if (!$content) {
			$this->success("评论内容不能为空", [], 2);
		}

		$Trends = \app\common\model\Trends::where(['id' => $trends_id])->find();

		if (!$Trends) {
			$this->success("动态不存在", [], 2);
		}
		if($Trends->comment_num){
	        $user_comment_num = Comment::where('trends_id', $trends_id)->where('user_id', $user_id)->where('parent_id', 0)->count();
            if($user_comment_num > $Trends->comment_num){
                $this->success("动态最多可评论".$Trends->comment_num."条", [], 2);
	        }
		}
      	
		if ($parent_id) {
			$comment = Comment::get($parent_id);
			if (!$comment) {
				$this->success("回复的评论不存在", [], 2);
			}
		} else {
			$comment = '';
		}

        $lucky_code = Comment::where('trends_id', $trends_id)->where('parent_id', 0)->max('lucky_code');
		$data = [
			'type'        => 1,
			'user_id'     => $user_id,
			'user2_id'    => $Trends->user_id,
			'trends_id'   => $trends_id,
			'circle_id'   => $Trends->circle_id,
			'parent_id'   => $comment ? $comment->id : 0,
			'hf_user_id'  => $comment ? $comment->user_id : 0,
			'content'     => $content,
			'lucky_code'  => ($lucky_code?$lucky_code:0) + 1,
			'create_time' => time()
		];
		$res = Comment::create($data);
		if ($res) {
			$Trends->setInc('comment', 1);//评论数量
			$Trends->setInc('vc_sum', 1);//评论和浏览综合次数
			//给话题增加评论数
			$list = TrendsHuati::where(['trends_id' => $trends_id])
			                                      ->select();
			foreach ($list as $k => $v) {
				$huati = Huati::get($v->huati_id);
				if ($huati) {
					$huati->setInc('comment', 1);
					$huati->setInc('vc_sum', 1);
				}
			}

			if ($parent_id) {
				$this->circulate($parent_id);
			}
			//发布系统消息
			send($user_id,$Trends->user_id,2,0);
			//动态被评论
			exps($Trends->circle_id, $Trends->user_id, 4);
			//评论他人动态
			exps($Trends->circle_id, $user_id, 8, 2);

			$this->success("发布成功");
		} else {
			$this->error('出差了');
		}
	}

	/**
	 * 评论列表
     * 
	 * @ApiMethod (POST)
	 * @param int $trends_id  动态id
	 * @param int $comment_id 评论id
	 * @param int $page       当前页码
	 * @param int $count      每页数量
	 */
    public function comment_list()
    {
        $user_id = $this->auth->id;
        $trends_id = $this->request->post('trends_id', 0);
        $comment_id = $this->request->post('comment_id', 0);
        $page = $this->request->post('page', 1);
        $count = $this->request->post('count', 10);

        $Trends = \app\common\model\Trends::where(['id' => $trends_id])->find();

        if (!$Trends) {
            $this->success("动态不存在", [], 2);
        }

        $where = [];
        $where['type'] = 1;
        $where['trends_id'] = $trends_id;
        //if($comment_id > 0) $where['parent_id'] = $comment_id;
        $where['parent_id'] = $comment_id;
        $circle_id = Config::get("site2.ggqz");

        $list = Comment::where($where)
              ->order("is_top desc") ->order("create_time desc")
            ->paginate($count, false, ["page" => $page]);
        foreach ($list as $k => $row) {
        	//if($row->parent_id > 0) unset($list[$k]);//保留一级评论，其他隐藏
            $row->append(['userinfo', 'comment']);
            $row->userinfo = $row->getuser($row,$user_id,$circle_id);
            $row->lucky_code = str_pad( $row->lucky_code, 6, '0', STR_PAD_LEFT);
            //二级评论
            /*$list2 = Comment::where(['parent_id' => $row->id])
                ->order("create_time desc")
                ->limit(3)
                ->select();*/
            $list2 = Comment::where(['parent_id' => $row->id])->order("create_time desc")->limit(1)->select();
            //新增3级评论
            foreach ($list2 as $k2 => $row2){
                $row2->append(['huifu3']);
                $list3 = Comment::where(['parent_id' => $row2->id])->order("create_time asc")->find();
                if($list3){
                    //清楚隐藏的评论
                    if($list3->is_hide == 0 && $list3->user_id != $user_id){
                        $row2->huifu3 = [];
                    }else{
                        $row2->huifu3 = $list3;
                    }
                }else{
                    $row2->huifu3 = [];
                }
                //清楚隐藏的评论
                if($row2->is_hide == 0 && $row2->user_id != $user_id){
                    unset($list2[$k2]);
                }

                $row2->append(['userinfo']);
                $row2->userinfo = $row2->getuser($row2,$user_id,$circle_id);
            }

            $row->comment = $list2;
            //清楚隐藏的评论
            if($row->is_hide == 0 && $row->user_id != $user_id){
                unset($list[$k]);
            }
        }
        $this->success("成功", $list);
    }

//	public function comment_list()
//	{
//
//		$user_id = $this->auth->id;
//		$trends_id = $this->request->post('trends_id', 0);
//		$comment_id = $this->request->post('comment_id', 0);
//		$page = $this->request->post('page', 1);
//		$count = $this->request->post('count', 10);
//
//		$Trends = \app\common\model\Trends::where(['id' => $trends_id])
//		                                  ->find();
//
//		if (!$Trends) {
//			$this->success("动态不存在", [], 2);
//		}
//
//		$where = [];
//		$where['type'] = 1;
//		$where['trends_id'] = $trends_id;
//		$where['parent_id'] = $comment_id;
//		$circle_id = Config::get("site.ggqz");
//
//		$list = Comment::where($where)
//		               ->order("create_time desc")
//		               ->paginate($count, false, ["page" => $page]);
//
//		foreach ($list as $row) {
//
//			$row->append(['userinfo', 'comment']);
//			$row->userinfo = $row->getuser($row,$user_id,$circle_id);
//
//			$list2 = Comment::where(['parent_id' => $row->id])
//			                       ->order("create_time desc")
//			                       ->limit(3)
//			                       ->select();
//			//新增
//			foreach ($list2 as $row2){
//
//				$row2->append(['huifu3']);
//
//				$huifu3 = Comment::where(['parent_id' => $row2->id])->order("create_time asc")->find();
//				if($huifu3){
//					$row2->huifu3 = $huifu3;
//				}else{
//					$row2->huifu3 = [];
//				}
//
//			}
//
//			$row->comment = $list2;
//
//		}
//
//		$this->success("成功", $list);
//
//	}

    /**
	 * 视频评论列表
     * 
	 * @ApiMethod (POST)
	 * @param int $trends_id  动态id
	 * @param int $comment_id 评论id
	 * @param int $page       当前页码
	 * @param int $count      每页数量
	 */
    public function video_comment_list()
    {
        $user_id = $this->auth->id;
        $trends_id = $this->request->post('trends_id', 0);
        $comment_id = $this->request->post('comment_id', 0);
        //$page = $this->request->post('page', 1);
        //$count = $this->request->post('count', 10);
        $Trends = \app\common\model\Trends::where(['id' => $trends_id])->find();
        if (!$Trends) {
            $this->success("动态不存在", [], 2);
        }

        $where = [];
        $where['type'] = 1;
        $where['trends_id'] = $trends_id;
        //if($comment_id > 0) $where['parent_id'] = $comment_id;
        $where['parent_id'] = $comment_id;
        $circle_id = Config::get("site2.ggqz");
        //$list = Comment::where($where)->order("create_time desc")->paginate($count, false, ["page" => $page]);
        $list = Comment::where($where)->order("create_time desc")->select();
        foreach ($list as $k => $row) {
        	//if($row->parent_id > 0) unset($list[$k]);//保留一级评论，其他隐藏
            $row->append(['userinfo', 'child']);
            $row->userinfo = $row->getuser($row,$user_id,$circle_id);
            //二级评论
            /*$list2 = Comment::where(['parent_id' => $row->id])
                ->order("create_time desc")
                ->limit(3)
                ->select();*/
            $list2 = Comment::where(['parent_id' => $row->id])->order("create_time desc")->select();
            //新增3级评论
            foreach ($list2 as $k2 => $row2){
                $row2->append(['child']);
                $list3 = Comment::where(['parent_id' => $row2->id])->order("create_time asc")->select();
                if($list3){
                    //清楚隐藏的评论
                    if($list3->is_hide == 0 && $list3->user_id != $user_id){
                        $row2->child = [];
                    }else{
                        $row2->child = $list3;
                    }
                }else{
                    $row2->child = [];
                }
                //清楚隐藏的评论
                if($row2->is_hide == 0 && $row2->user_id != $user_id){
                    unset($list2[$k2]);
                }

                $row2->append(['userinfo']);
                $row2->userinfo = $row2->getuser($row2,$user_id,$circle_id);
            }

            $row->child = $list2;
            //清楚隐藏的评论
            if($row->is_hide == 0 && $row->user_id != $user_id){
                unset($list[$k]);
            }
        }
        $this->success("成功", $list);
    }
    
	/**
	 * 记录查看通知公告弹窗
     * 
	 * @ApiMethod (POST)
	 * @param int $noticle_id  通知id，必填
	 * @param int $circle_id   圈子id，必填
	 */
	public function add_noticelog()
	{
		$user_id = $this->auth->id;
		$noticle_id = $this->request->post('noticle_id', 0);
		$circle_id = $this->request->post('circle_id', 0);

		if (empty($noticle_id) || empty($circle_id)) {
			$this->success("参数错误", [], 2);
		}

		$noticelog = Noticelog::where(['user_id' => $user_id, 'circle_id' => $circle_id, 'noticle_id' => $noticle_id])->find();
		if (!$noticelog) {
			Noticelog::insert(['user_id' => $user_id, 'circle_id' => $circle_id, 'noticle_id' => $noticle_id, 'createtime' => time()]);
			$this->success("成功");
		} else {
			$this->success("已记录过");
		}
	}

	/**
	 * 查看答题次数
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id   圈子id，必填
	 */
	public function answer_num()
	{
		$user_id = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$circle = Circle::get($circle_id);
		if (!$circle) {
			$this->success('圈子不存在', [], 2);
		}

		$site = Config::get("site2");
		$day = date("Y-m-d");
		$answer = Answer::where(['user_id' => $user_id, 'circle_id' => $circle_id, 'day' => $day])->find();
		if (empty($answer)) {
			$count = Answer::where(['user_id' => $user_id, 'circle_id' => $circle_id])->count();
			if ($count >= $site['answer_day']) {
				$this->success("答题次数已用完", [], 2);
			} else {
				$this->success("继续答题");
			}
		} else {
			if ($answer->num >= $site['answer_num']) {
				$this->success("今日答题次数已用完", [], 2);
			} else {
				$this->success("继续答题");
			}
		}
	}

	/**
	 * 记录答错次数
     * 
	 * @ApiMethod (POST)
	 * @param int $circle_id   圈子id，必填
	 */
	public function answer_log()
	{
		$user_id = $this->auth->id;
		$circle_id = $this->request->post('circle_id', 0);
		$circle = Circle::get($circle_id);
		if (!$circle) {
			$this->success('圈子不存在', [], 2);
		}

		$site = Config::get("site2");
		$day = date("Y-m-d");
		$answer = Answer::where(['user_id' => $user_id, 'circle_id' => $circle_id, 'day' => $day])->find();
		//判断今天有没有答题
		if ($answer) {
			if ($answer->num >= $site['answer_num']) {
				$this->success("今日答题次数已用完", [], 2);
			}
			$res = $answer->setInc('num', 1);
		} else {
			$res = Answer::create(['user_id' => $user_id, 'circle_id' => $circle_id, 'day' => $day]);
		}

		if ($res) {
			$this->success("记录成功");
		} else {
			$this->success("记录失败", [], 2);
		}
	}

	//敏感词汇判断
	private function keyword($content){
		$keyword = Config::get("site2.prohibit");
		$m = "";
		foreach ($keyword as $k => $v) { //根据数组元素数量执行for循环
			if (substr_count($content, $v) > 0) {
				$m .= $v.',';
			}
		}
		return $m;
	}

	/**
	 * 评论删除
     * 
	 * @ApiMethod (POST)
	 * @param int $comment_id   评论id，必填
	 */
	public function comment_delete()
	{
		$user_id = $this->auth->id;
		$comment_id = $this->request->post('comment_id');
		$comment = Comment::get($comment_id);
		if (!$comment) {
			$this->success('评论不存在', [], 2);
		}
	}

	/**
	 * 查询关联商品信息
	 * @ApiMethod (POST)
	 */
	public function get_scenic_list() {
		$list = Scenic2::where(['show_status' => 1])
		                ->order('weigh desc')
		                ->select();
		$this->success("获取成功",$list);
	}
}
